package org.subside.config;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 在Controller方法调用前执行
//        String s1 = JSONUtils.toJSONString(request);
//        String s2 = JSONUtils.toJSONString(handler);
//        System.out.println("方法调用前拦截!");
//        log.info(((HandlerMethod) handler).getBean().getClass().getName());
//        log.info(((HandlerMethod) handler).getMethod().getName());
//        Map<String, String[]> map = request.getParameterMap();
//        for(Map.Entry<String,String[]>m:map.entrySet()){
//            String key = m.getKey();
//            String[] value = m.getValue();
//        }
//        request.setAttribute("startTime", System.currentTimeMillis());
//        String s =new String("sss".getBytes(), StandardCharsets.UTF_16);
//
//        BufferedReader reader = request.getReader();
//        StringBuilder requestBody = new StringBuilder();
//        String line;
//        while ((line = reader.readLine()) != null) {
//            requestBody.append(line);
//        }
//        String requestBodyString = requestBody.toString();
//// 将RequestBody参数转换为JSON对象
//        JSONObject requestBodyJson = JSONObject.parseObject(requestBodyString);
//// 修改JSON对象中的某个属性
//        requestBodyJson.put("key", "new value");
//
//// 将修改后的JSON对象转换回字符串
//        String modifiedRequestBodyString = requestBodyJson.toString();

       return true; // 返回 true 表示继续执行Controller方法，返回 false 表示中断
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在Controller方法调用后、视图渲染前执行
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在视图渲染完成后执行，通常用于资源清理等操作
    }
}
